/*
* 路由的拦截
* */
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import router from './router'
import store from './store'

// 路由的白名单
const whiteList = ['/login']
NProgress.configure({ showSpinner: false })
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken('token')
  if (hasToken) {
    // if (to.path === '/login') {
    //   next({ path: '/' })
    // }
    const role = (getToken('role'))
    const roles = await store.dispatch('permission/generateRoutes', role)
    // console.log('已开始的', router)
    console.log('roles', roles)
    // router.addRoute(...roles)
    // console.log('11111', router.options.routes)
    router.addRoutes(roles)
    console.log('之后的', router)
    next()
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
